<?php

include_once('/usr/share/php/symfony/yaml/sfYaml.class.php');

class PluginsfFormGuiQuestion extends BasesfFormGuiQuestion {

    static protected $validators = array(
        'Input' => 'sfValidatorString',
        'InputCheckbox' => 'sfValidatorBoolean',
        'InputCheckboxCollection' => 'sfValidatorBoolean',
        'InputFile' => 'sfValidatorSaveFile',
        'SaveFile' => 'sfValidatorSaveFile',
        'Select' => 'sfValidatorChoice',
        'SelectMany' => 'sfValidatorChoice',
        'Textarea' => 'sfValidatorString'
    );
      
    public function __toString() {
        return $this->getName();
    }
    
    public function setResponseQuestion($response, $form) {
    
        $responseQuestion = $this->getResponseQuestion($response);
        if($this->getWidget() == 'SaveFile') {
            $value = sfConfig::get('sf_upload_dir_name').'/'.basename($form->getValue($this->getId()));
        }
        else {
            $value = $form->getValue($this->getId());
        }
        $responseQuestion->setValue($value);
        $responseQuestion->save();
    }
    
    public function getResponseQuestion($response) {
        
        $c = new Criteria;
        $c->add(sfFormGuiResponseQuestionPeer::QUESTION_ID, $this->getId());
        $c->add(sfFormGuiResponseQuestionPeer::RESPONSE_ID, $response->getId());
        
        $responseQuestion = sfFormGuiResponseQuestionPeer::doSelectOne($c);
        if(!$responseQuestion) {
            $responseQuestion = new sfFormGuiResponseQuestion;
            $responseQuestion->setQuestionId($this->getId());
            $responseQuestion->setResponseId($response->getId());
        }
        return $responseQuestion;
    }
        
    public function getFormFieldObject() {
        $classname = 'sfWidgetForm'.sfInflector::classify($this->getWidget());
        if( !class_exists($classname) ) {
            throw new sfConfigurationException(sprintf('The widget "%s" does not exist.', $classname));
        }
        $options = array();
        foreach($this->getSfformGuiQuestionScopedParameters('widget') as $parameter) {
            $options[$parameter->getKey()] = sfYAML::load($parameter->getValue());
        }
        $widget = new $classname($options);
        
        return $widget;
    }
    
    public function getFormFieldValidator() {
        
        $classname = self::$validators[$this->getWidget()];
        
        if( !class_exists($classname) ) {
            throw new sfConfigurationException(sprintf('The validator "%s" does not exist.', $classname));
        }
        
        $options = array();
        foreach($this->getSfformGuiQuestionScopedParameters('validator') as $parameter) {
            if($parameter->getKey() == 'choices') {
                $options[$parameter->getKey()] = array_keys(sfYAML::load($parameter->getValue()));
            }
            else {
                $options[$parameter->getKey()] = sfYAML::load($parameter->getValue());
            }
        }
        $options['required'] = $this->getRequired();
        $validator = new $classname($options);
        
        return $validator;
    }
    
    public function getSfformGuiQuestionScopedParameters($scope='') {
        $c = new Criteria;
        $c->add( sfFormGuiQuestionParameterPeer::TYPE, $this->getWidget());
        $c->add( 
            $c->getNewCriterion(sfFormGuiQuestionParameterPeer::SCOPE, $scope )->addOr(
            $c->getNewCriterion(sfFormGuiQuestionParameterPeer::SCOPE, '' )
        ));
        return $this->getSfformGuiQuestionParameters($c);
    }
    
    
    public function save($con = null)
    {
      // New records need to be initialized with rank = maxRank +1
      if(!$this->getId())
      {
        $con = Propel::getConnection(sfFormGuiQuestionPeer::DATABASE_NAME);
        try
        {
          $con->begin();
     
          $this->setRank(sfFormGuiQuestionPeer::getMaxRank()+1);
          parent::save();
     
          $con->commit();
        }
        catch (Exception $e)
        {
          $con->rollback();
          throw $e;
        }
      }
      else
      {
        parent::save(); 
      }
    } 
 
    public function delete($con = null)
    {  
      $con = Propel::getConnection(PagePeer::DATABASE_NAME);
      try
      {
        $con->begin();
     
        // decrease all the ranks of the page records of the same category with higher rank 
        $sql = 'UPDATE '.sfFormGuiQuestionPeer::TABLE_NAME.' SET '.sfFormGuiQuestionPeer::RANK.' = '.sfFormGuiQuestionPeer::RANK.' - 1 WHERE '.sfFormGuiQuestionPeer::RANK.' > '.$this->getRank();
        $con->executeQuery($sql);
        // delete the item
        parent::delete();
     
        $con->commit();
      }
      catch (Exception $e)
      {
        $con->rollback();
        throw $e;
      }
    }
    
    public function getResponses($criteria=null) {
        if(!$criteria) {
            $c = new Criteria;
        }
        else {
            $c = clone $criteria;
        }
        $c->add(sfFormGuiResponseQuestionPeer::QUESTION_ID, $this->getId());
        $responses = sfFormGuiResponseQuestionPeer::doSelect($c);
        return $responses;
    }
    
    public function getStats() {
        //$c = new Criteria;
        //$c->addGroupByColumn(sfFormGuiResponseQuestionPeer::VALUE);
        $responses = $this->getResponses();
        
        $stats = array();
        $keys = array();
        $index = 0;
        foreach($responses as $response) {
            sfContext::getInstance()->getLogger()->warning($response->getValue());
            sfContext::getInstance()->getLogger()->warning($index);
            sfContext::getInstance()->getLogger()->warning(print_r($keys,true));
            if(!array_key_exists($response->getValue(), $keys)) {
                $keys[$response->getValue()] = $index++;
            }
            if(array_key_exists($keys[$response->getValue()], $stats)) {
                $stats[$keys[$response->getValue()]]++;
            }
            else {
                $stats[$keys[$response->getValue()]] = 1;
            }
        }
        return empty($stats) ? null : array( 
            'keys' => array_keys($keys),
            'values' => $stats
        );
    }
}
